<?php
	####################################################
	# library import and object instance.              #
	####################################################
	include_once('./common.php');


	####################################################
	# request data($_POST AND $_GET FROM $_REQUEST)    #
	####################################################
	# REQUEST(get and post variables)
	$req = Request::clean_request($_REQUEST);

	# GET(url variables)

	# POST(form variables)

	# Validation(special case validate)

	####################################################
	# implementation                                   #
	####################################################
	$html->set_title("nScaffold");
	$html->set_script("{$JS}jquery.1.7.1.min.js");
	$html->custom_js("{$JS}lib.control.js");
	$html->set_style("{$CSS}basic.css");
	$html->html_header();

	# 변수 & 인스턴스
	$message	= '';
	$table		= array();
	$st			= new ScaffoldTool();

	$data = $req['sql'];

	//Nlog::xmp($ret);

	# 테이블 배열 제작
	$data_lines = explode("\n", $data);

	# 인젝션 방지. --을 제거, insert into 제거.
	foreach($data_lines as $key => $val) {
		$val = trim($val);
		if ($val[0] == '-' && $val[1] == '-') {
			unset($data_lines[$key]);
		} elseif (stripos($val, 'insert into')) {
			unset($data_lines[$key]);
		}
	}

	# table을 만들어주는 부분
	# DB
	//$table['include']			= $req['include'];
	$table['table_name']		= $req['table_name'];
	$table['pk_key']			= $req['pk_key'];

	# APP & query file
	$table['app_prefix']		= $req['app_prefix'];
	$table['query_file']		= sprintf("%squery.sql", $table['app_prefix']);
	$table['common_page']		= $req['app_prefix'].$req['common_page'];
	$table['list_page']			= $req['app_prefix'].$req['list_page'];
	$table['create_page']		= $req['app_prefix'].$req['create_page'];
	$table['retrieve_page']		= $req['app_prefix'].$req['retrieve_page'];
	$table['update_page']		= $req['app_prefix'].$req['update_page'];
	$table['delete_page']		= $req['app_prefix'].$req['delete_page'];
	$table['create_proc_page']	= $req['app_prefix'].str_replace('.php', '_proc.php', $req['create_page']);
	$table['update_proc_page']	= $req['app_prefix'].str_replace('.php', '_proc.php', $req['update_page']);
	$table['delete_proc_page']	= $req['app_prefix'].str_replace('.php', '_proc.php', $req['delete_page']);

	# 테이블을 생성한다.
	$table['query'] = str_replace("\'","'",$_REQUEST['sql']);
	if($req['scaffold_info'] == 'ayaxyz1425'){
		$ret = $db->query("". $table['query'] ."");
		$message = "application created, you visit fallowing link to : <a href=\"./{$table['list_page']}\">{$table['list_page']}</a>";
		$delete_table_name = sprintf("<input type=\"hidden\" name=\"target_table\" value=\"%s\" />", $req['table_name']);
	} else {
		$message = "you mean not run query. but make files...";
	}

	# database type 파악
	$max = count($data_lines);
	for ($i = 1; $i < $max; $i++ ) {
		if ( strpos( trim($data_lines[$i]), "`") === 0) {
			$col = $st->find_text(trim($data_lines[$i]));
			$blob = ( stripos($data_lines[$i], 'TEXT') || stripos($data_lines[$i], 'BLOB') ) ? 1 : 0;
			$enum = ( stripos($data_lines[$i], 'enum') ) ? 1 : 0;
			$datetime = ( stripos($data_lines[$i], 'DATETIME') ) ? 1 : 0;

			//eval( "\$table['$col'] = array('blob' => $blob, 'enum' => $enum, 'datetime' => $datetime );");
			$table[$col] = array('blob' => $blob, 'enum' => $enum, 'datetime' => $datetime );
			if($enum){
				$tmpval = substr($data_lines[$i], (strpos($data_lines[$i],"(")+1));
				$values = substr($tmpval, 0, (strpos($tmpval,")")));
				$values = str_replace("'","",$values);
				$values = str_replace("\\","",$values);
				$values = explode(",",$values);
				$table[$col]['enum_data'] = $values;
			}
		}
	}

	//Nlog::xmp($table);

	# make instance
	$s = new Scaffold($table);

	# downlaod 준비
	$createZip = new CreateZip();
	$createZip -> addFile($table['query_file'],			StrFormat::multy_line_rtrim($table['query']));
	$createZip -> addFile($table['common_page'],		StrFormat::multy_line_rtrim($s->common_page()));
	$createZip -> addFile($table['list_page'],			StrFormat::multy_line_rtrim($s->list_page()));
	$createZip -> addFile($table['create_page'],		StrFormat::multy_line_rtrim($s->create_page()));
	$createZip -> addFile($table['retrieve_page'],		StrFormat::multy_line_rtrim($s->retrieve_page()));
	$createZip -> addFile($table['update_page'],		StrFormat::multy_line_rtrim($s->update_page()));
	$createZip -> addFile($table['delete_page'],		StrFormat::multy_line_rtrim($s->delete_page()));
	$createZip -> addFile($table['create_proc_page'],	StrFormat::multy_line_rtrim($s->create_proc_page()));
	$createZip -> addFile($table['update_proc_page'],	StrFormat::multy_line_rtrim($s->update_proc_page()));
	$createZip -> addFile($table['delete_proc_page'],	StrFormat::multy_line_rtrim($s->delete_proc_page()));
	$fname = sprintf("temp/%sapplication%s.zip", $req['app_prefix'], date("YmdHis"));
	$fd = fopen ($fname, "wb");
		  fwrite ($fd, $createZip->getZippedfile());
		  fclose ($fd);

	# make view
	$out .="<table width=\"100%\" border=\"1\" cellspacing=\"3\" cellpadding=\"3\">
		<colgroup>
			<col width=\"10%\" />
			<col width=\"90%\" />
		</colgroup>";
	$out .= "<tr>";
	$out .= "<th>";
	$out .= "link";
	$out .= "</th>";
	$out .= "<td>";
	$out .= $message;
	$out .= "</td>";
	$out .= "</tr>";
	$out .="<tr>";
	$out .="	<th>LIST <br />{$table['list_page']}</th>";
	$out .="	<td>";
	$out .= "<xmp class=\"code\" id=\"list\">";
	$out .= StrFormat::multy_line_rtrim($s->list_page());
	$out .= "</xmp>";
	$out .="	</td>";
	$out .="</tr>";
	$out .="<tr>";

	$out .="<tr>";
	$out .="	<th>CREATE <br />{$table['create_page']}</th>";
	$out .="	<td>";
	$out .= "<xmp class=\"code\" id=\"create\">";
	$out .= StrFormat::multy_line_rtrim($s->create_page());
	$out .= "</xmp>";
	$out .="	</td>";
	$out .="</tr>";
	$out .="<tr>";
	$out .="	<th>RETRIEVE <br />{$table['retrieve_page']}</th>";
	$out .="	<td>";
	$out .= "<xmp class=\"code\" id=\"retrieve\">";
	$out .= StrFormat::multy_line_rtrim($s->retrieve_page());
	$out .= "</xmp>";
	$out .="	</td>";
	$out .="</tr>";
	$out .="<tr>";
	$out .="	<th>UPDATE <br />{$table['update_page']}</th>";
	$out .="	<td>";
	$out .= "<xmp class=\"code\" id=\"update\">";
	$out .= StrFormat::multy_line_rtrim($s->update_page());
	$out .= "</xmp>";
	$out .="	</td>";
	$out .="</tr>";
	$out .="<tr>";
	$out .="	<th>DELETE <br />{$table['delete_page']}</th>";
	$out .="	<td>";
	$out .= "<xmp class=\"code\" id=\"delete\">";
	$out .= StrFormat::multy_line_rtrim($s->delete_page());
	$out .= "</xmp>";
	$out .="	</td>";
	$out .="</tr>";

	$out .="	<th>CREATE PROC<br />{$table['create_proc_page']}</th>";
	$out .="	<td>";
	$out .= "<xmp class=\"code\" id=\"create_proc\">";
	$out .= StrFormat::multy_line_rtrim($s->create_proc_page());
	$out .= "</xmp>";
	$out .="	</td>";
	$out .="</tr>";
	$out .="<tr>";
	$out .="	<th>UPDATE PROC <br />{$table['update_proc_page']}</th>";
	$out .="	<td>";
	$out .= "<xmp class=\"code\" id=\"update_proc\">";
	$out .= StrFormat::multy_line_rtrim($s->update_proc_page());
	$out .= "</xmp>";
	$out .="	</td>";
	$out .="</tr>";
	$out .="<tr>";
	$out .="	<th>DELETE PROC <br />{$table['delete_proc_page']}</th>";
	$out .="	<td>";
	$out .= "<xmp class=\"code\" id=\"delete_proc\">";
	$out .= StrFormat::multy_line_rtrim($s->delete_proc_page());
	$out .= "</xmp>";
	$out .="	</td>";
	$out .="</tr>";
	$out .="<tr>";
	$out .="	<td colspan=\"2\" align=\"right\"><button onclick=\"Mover.href('./nscaffolding.php')\" class=\"w200\">go back</button></td>";
	$out .="</tr>";
	$out .="</table>";

	# create file
	IoFileAndDir::nfilewriter($table['query_file'],			$table['query']);
	IoFileAndDir::nfilewriter($table['common_page'],		$s->common_page());
	IoFileAndDir::nfilewriter($table['list_page'],			$s->list_page());
	IoFileAndDir::nfilewriter($table['create_page'],		$s->create_page());
	IoFileAndDir::nfilewriter($table['retrieve_page'],		$s->retrieve_page());
	IoFileAndDir::nfilewriter($table['update_page'],		$s->update_page());
	IoFileAndDir::nfilewriter($table['delete_page'],		$s->delete_page());
	IoFileAndDir::nfilewriter($table['create_proc_page'],	$s->create_proc_page());
	IoFileAndDir::nfilewriter($table['update_proc_page'],	$s->update_proc_page());
	IoFileAndDir::nfilewriter($table['delete_proc_page'],	$s->delete_proc_page());

	# 다운로드/삭제를 위한 값 생성
	$all = array();
	$all[] = $table['query_file'];
	$all[] = $table['common_page'];
	$all[] = $table['list_page'];
	$all[] = $table['create_page'];
	$all[] = $table['retrieve_page'];
	$all[] = $table['update_page'];
	$all[] = $table['delete_page'];
	$all[] = $table['create_proc_page'];
	$all[] = $table['update_proc_page'];
	$all[] = $table['delete_proc_page'];
	$target_files = NArray::implode_separate($all);

?>
	<h1>nScaffold - approaching compleate</h1>
	<style type="text/css">
		span{color:silver;}
		xmp{background-color:#6A6D7B;width:99%;color:white;}
	</style>
	<?=$out?>
	<?=NForm::open("./nscaffolding_delete_proc.php", FALSE);?>
		<?=@$delete_table_name?>
		<input type="hidden" name="target_files" value="<?=$target_files?>" />
		<?=NTool::submit_btn("delete creation files");?>
	</form>
	<?=NForm::open("./nscaffolding_download_proc.php", FALSE);?>
		<input type="hidden" name="target_files" value="<?=$fname?>" />
		<?=NTool::submit_btn("download files");?>
	</form>
<?php
	$html->html_footer();
?>